package de.bazinga.rotw.effects;

import com.jme.bounding.BoundingBox;
import com.jme.math.Triangle;
import com.jme.math.Vector3f;
import com.jme.scene.Node;
import com.jme.scene.shape.Quad;
import com.jme.scene.state.BlendState;

import de.bazinga.rotw.game.Game;
import de.bazinga.rotw.texture.TextureCache;

public class BulletHoles {
	
	private static BulletHoles instance = new BulletHoles();
	
	
	private Quad[] bulletHoles = new Quad[50];
	
	private int currentBulletHole = 0;
	
	private BulletHoles() {
		
	}
	
	public static BulletHoles getInstance() {
		return instance;
	}
	
	public void init(Node rootNode) {
		// Init BulletHoles
		BlendState bs = Game.getGame().getDisplay().getRenderer().createBlendState();
		bs.setBlendEnabled(true);
		bs.setSourceFunction(BlendState.SourceFunction.SourceAlpha);
		bs.setDestinationFunction(BlendState.DestinationFunction.OneMinusSourceAlpha);
		bs.setTestEnabled(true);
		bs.setTestFunction(BlendState.TestFunction.GreaterThan);
		
		for(int i=0;i<50;i++) {
			bulletHoles[i] = new Quad("bulletHole",0.1f,0.1f);
			//quad.setRenderQueueMode(Renderer.QUEUE_ORTHO);
			bulletHoles[i].setLocalTranslation(new Vector3f(0,-999f,0));
			
			bulletHoles[i].setRenderState(TextureCache.getInstance().getTexture("texture/bulletHole.png"));
			
			bulletHoles[i].setRenderState(bs);
			
			bulletHoles[i].setModelBound(new BoundingBox());
			bulletHoles[i].updateModelBound();
			
			//quad.setLightCombineMode(Spatial.LightCombineMode.Off);
			bulletHoles[i].updateRenderState();
			
			rootNode.attachChild(bulletHoles[i]);
		}
	}
	
	public void setBulletHole(Vector3f location, Triangle tri) {
		bulletHoles[currentBulletHole].setLocalTranslation(location);
		
		tri.calculateNormal();
		bulletHoles[currentBulletHole].lookAt(
				bulletHoles[currentBulletHole].getLocalTranslation().add(tri.getNormal()),
				Vector3f.UNIT_Y);
		
		bulletHoles[currentBulletHole].updateRenderState();
		
		currentBulletHole++;
		if(currentBulletHole == bulletHoles.length)
			currentBulletHole = 0;
	}
}
